package com.neeraj.SharingArtifacts;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class UseCamera extends Activity implements OnTouchListener, LocationListener, OnCancelListener {
	
	private static final String DEBUG_TAG = "USE CAMERA";
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;
	private static final int MEDIA_TYPE_IMAGE = 1;
	private static final int WAIT_DIALOG_ID = 1;
	private Uri fileUri;	
	private LocationManager locationManager;
	private Location location;
	private String bestProvider;	
	
	RelativeLayout rel;
	DatabaseHelper dbHelper;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.use_camera);

        rel = (RelativeLayout) findViewById(R.id.relativeLayoutTap);
        rel.setOnTouchListener(this);
        
        if (!Geocoder.isPresent()){
        	Toast.makeText(getBaseContext(),
        	"Sorry! Geocoder service not Present.",
        	Toast.LENGTH_LONG).show();
        }
        showDialog(WAIT_DIALOG_ID);
 		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);     		

   		Criteria criteria = new Criteria();
   		criteria.setAccuracy(Criteria.ACCURACY_COARSE);
  		criteria.setAccuracy(Criteria.ACCURACY_FINE);
   		bestProvider = locationManager.getBestProvider(criteria, false);

   		location = locationManager.getLastKnownLocation(bestProvider); 
   		
		Log.d("UseCamera", "Activity started");		
	}	
	
	@Override
	public void onStart()
	{
		try {
			super.onStart();
			dbHelper=new DatabaseHelper(this);
			dbHelper.insertTypeData();
		} catch(Exception ex) {			
			CatchError(ex.toString());
		}
	}
	
	@Override
    protected void onResume() {
		super.onResume();		
		locationManager.requestLocationUpdates(bestProvider, 1000, 1, this);
	}

	/** Stop the updates when Activity is paused */
	@Override
	protected void onPause() {
		super.onPause();
		locationManager.removeUpdates(this);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
//		super.onActivityResult(requestCode, resultCode, data);
		Log.d(DEBUG_TAG, "ResultCode:"+resultCode);
		if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
			if(resultCode == Activity.RESULT_OK){
				Log.d(DEBUG_TAG, "picture saved i guess!");
				Toast.makeText(this, "Image saved to:\n" + fileUri.getPath(), Toast.LENGTH_LONG).show();
								
		   		Log.d(DEBUG_TAG, "in on create" + location.getLatitude() + ", " + location.getLongitude());
		   		saveAttributes();
			}
			else if(resultCode == Activity.RESULT_CANCELED) {
				Log.d(DEBUG_TAG, "picture capture cancelled!");
				Toast.makeText(this, "Image capture cancelled", Toast.LENGTH_LONG).show();
			}
			else
				Toast.makeText(this, "Image capture failed", Toast.LENGTH_LONG).show();

		}			
	}
		
	/** Create a file Uri for saving an image or video */
	private static Uri getOutputMediaFileUri(int type){
	      return Uri.fromFile(getOutputMediaFile(type));
	}

	/** Create a File for saving an image */
	private static File getOutputMediaFile(int type){
	    // To be safe, you should check that the SDCard is mounted
	    // using Environment.getExternalStorageState() before doing this.

	    File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(
	              Environment.DIRECTORY_DCIM), "SharingArtifacts/image");

	    // Create the storage directory if it does not exist
	    if (! imageStorageDir.exists()){
	        if (! imageStorageDir.mkdirs()){
	            Log.d(DEBUG_TAG, "failed to create directory");
	            return null;
	        }
	    }
	    // Create a media file name
	    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date());
	    File mediaFile;
	    if (type == MEDIA_TYPE_IMAGE){
	        mediaFile = new File(imageStorageDir.getPath() + File.separator +
	        "IMG_"+ timeStamp + ".jpg");
	    } else {
	        return null;
	    }

	    return mediaFile;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		Log.d(DEBUG_TAG, "Going For Camera Activity");
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

	    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
	    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name

	    // start the image capture Intent
	    startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
		return false;
	}

	private String getDate() {
		String date;
		final Calendar c = Calendar.getInstance();
		int myYear = c.get(Calendar.YEAR);
		int myMonth = c.get(Calendar.MONTH);
		String monthStr=null;
//		String dayStr = null;
		if(myMonth < 10 )
			monthStr = "0"+String.valueOf(myMonth+1);
		int myDay = c.get(Calendar.DAY_OF_MONTH);
//		if(myDay < 10)
//			dayStr = "0"+String.valueOf(myDay);
		
		date = String.valueOf(myYear) + "-"
			       + monthStr + "-" + String.valueOf(myDay);
		
		return date;
	}
	
	void CatchError(String Exception) {	    	
    	Dialog diag=new Dialog(this);
    	diag.setTitle("Error!!!");
    	TextView txt=new TextView(this);
    	txt.setText(Exception);
    	diag.setContentView(txt);
    	diag.show();
    }
	
	void saveAttributes() {
		Log.d(DEBUG_TAG, "in save attributes!!!");
		Bundle b = new Bundle();
		b.putDouble("latitude", getLatitude());
		b.putDouble("longitude", getLongitude());
		b.putDouble("altitude", getAltitude());
		b.putLong("utc_time", getTime());
		b.putString("date", getDate());
		b.putString("artifactType", "image");
		b.putString("content", fileUri.getPath());
		b.putString("content_file_name", fileUri.getLastPathSegment());
		b.putInt("isUpload", 0);
		
		dbHelper.insertData(b, MEDIA_TYPE_IMAGE);
	}
	
	protected Dialog onCreateDialog(int id) {
   	 // TODO Auto-generated method stub
   	 Dialog alertDialog = null;;
   	    switch(id) {
   	    case WAIT_DIALOG_ID:
   			alertDialog = new ProgressDialog(this);
   			((ProgressDialog)alertDialog).setMessage("Waiting for GPS location...");
   			alertDialog.setCancelable(true);
   			alertDialog.setOnCancelListener(this);
   			break;
   	    }
   	    return alertDialog;
   }
   
	@Override
	public void onCancel(DialogInterface dialog) {
		// TODO Auto-generated method stub
		removeDialog(WAIT_DIALOG_ID);
	}

	@Override
	public void onLocationChanged(Location loc) {
		// TODO Auto-generated method stub
		location = loc;
	    location.getLatitude();
	    location.getLongitude();
//	    dismissDialog(WAIT_DIALOG_ID);
	    removeDialog(WAIT_DIALOG_ID);
	    String Text = "My current location is:" + "Latitude = " + 
	    		location.getLatitude() + ",Longitude = " + location.getLongitude();
	    Toast.makeText( this, Text, Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		Toast.makeText( this, "Gps Disabled", Toast.LENGTH_SHORT ).show();
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		Toast.makeText( this, "Gps Enabled", Toast.LENGTH_SHORT ).show();
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub		
	}
	
	double getLatitude() {
		return location.getLatitude();
	}
	
	double getLongitude() {
		return location.getLongitude();
	}
	
	double getAltitude() {
		return location.getAltitude();
	}
	
	long getTime() {
		return location.getTime();
	}
}
